<template>
  <div class="login">
    <div class="login-form">
      <h2 class="login-title">Template Login</h2>
      <a-form :model="form">
        <a-form-item field="username">
          <a-input
            v-model="form.username"
            placeholder="Username"
            @pressEnter="handleLogin"
          >
            <template #prefix>
              <icon-user />
            </template>
          </a-input>
        </a-form-item>
        <a-form-item field="password">
          <a-input-password
            v-model="form.password"
            placeholder="Password"
            @pressEnter="handleLogin"
          >
            <template #prefix>
              <icon-lock />
            </template>
          </a-input-password>
        </a-form-item>
      </a-form>
      <a-button
        type="primary"
        @click="handleLogin"
        :disabled="loading"
      >
        {{ loading ? "登录中..." : "登录" }}
      </a-button>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { reactive, ref } from "vue";
  import { Message } from "@arco-design/web-vue";
  import { login } from "@/api/modules/user";
  import { UserInfo } from "@/types/user";
  import { useUserStore } from "@/store/modules/user";
  import { useJumper } from "@/hooks/useJumper";

  type LoginUser = {
    token: string;
    user: UserInfo;
  };

  const userStore = useUserStore();
  const jumper = useJumper();

  const form = reactive({
    username: "",
    password: "",
  });
  const loading = ref<boolean>(false);

  const handleLogin = async () => {
    if (!form.username) {
      Message.error("请输入用户名");
      return;
    }
    if (!form.password) {
      Message.error("请输入密码");
      return;
    }
    try {
      loading.value = true;
      const res = await login<LoginUser>(form);
      userStore.loginSuccess(res.data?.user || {}, res.data?.token || "");
      jumper.push("/");
    } catch (e) {
      console.error(e);
    } finally {
      loading.value = false;
    }
  };
</script>
